package com.ciaojian.core.util;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ciaojian.core.model.fulu.FuluRequest;
import net.sf.json.JSONObject;

public class FuluUtil {


    public static FuluRequest newFuluRequest(String json,String method,String appKey,String sysSecret) {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = df.format(now);

        return FuluRequest.builder()
                .app_key(appKey)
                .method(method)
                .timestamp(timestamp)
                .version("2.0")
                .format("json")
                .charset("utf-8")
                .sign_type("md5")
                .sign(Sign(sysSecret,timestamp,json,method,appKey))
                .app_auth_token("")
                .biz_content(json)
                .build();
    }

    public static String Sign(String sysSecret,String timestamp,String json,String method,String appkey){
        Map<String, String> map = new HashMap<String, String>();
        map.put("app_key",appkey);
        map.put("method", method);
        map.put("timestamp", timestamp);
        map.put("version", "2.0");
        map.put("format", "json");
        map.put("charset", "utf-8");
        map.put("sign_type", "md5");
        map.put("app_auth_token", "");
        map.put("biz_content", json);

//        JSONObject resultJson = JSONObject.fromObject(map);
        JSONObject resultJson = JSONObject.fromObject(map);
        char[] s = com.alibaba.fastjson.JSONObject.toJSONString(resultJson, SerializerFeature.WriteMapNullValue).toCharArray();
        Arrays.sort(s);

        String outputSignOriginalStr = new String(s) + sysSecret;
        String sign = MD5Utils.MD5(outputSignOriginalStr);
        return sign;
    }

}
